import { FAQList } from "../../../api/ask"
import { shareAppMessageSet } from "../../../utils/config"
import { dataCollection } from "../../../utils/dataCollection"

interface QuestionProps {
  title: string
  content: string
  unfold: boolean
}

interface DataProps {
  list: QuestionProps[]
  unfoldIndex: number //默认打开的N个
  current: number
  total: number
}

Page({

  /**
   * 页面的初始数据
   */
  data: <DataProps>{
    list: [],
    unfoldIndex: 0,
    current: 1,
    total: 0,
    themeCode:''
  },
  onLoad(options) {
    //从本地获取当前选择的城市编码
    this.setData({
      themeCode: wx.getStorageSync('themeCode')
    })

    this.getFAQList(()=>{
      if ('id' in options) {
        const arr = this.data.list
        arr.forEach((item: any, index: number) => {
          if (item.id === options.id) {
            item.unfold = true
          }
        })  
        this.setData({
          list: arr
        })
      }
    })
    
  },
  //点击展开或者关闭
  onUnfold(res: any) {
    const index = res.currentTarget.dataset.index
    const arr = this.data.list
    arr[index].unfold = !arr[index].unfold

    arr.forEach((item: any, i: number) => {
      if (i === index) {
        item.unfold = true
      } else {
        item.unfold = false
      }
    })

    this.setData({
      list: arr
    })
  },
  //获取回答的数据
  getFAQList(callback=()=>{}) {
    FAQList(this.data.current).then(res => {
      let i = this.data.current
      i++
      const list: any[] = this.data.list
      if (this.data.current === 1) {
        list.length = 0
      }
      list.push(...res.result.records)

      this.setData({
        current: i,
        total: res.result.total,
        list: [...list]
      })
      callback()
    })
  },
  bindscrolltolower() {
    if (this.data.list.length < Number(this.data.total)) {
      this.getFAQList()
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {...shareAppMessageSet()}
  },
  onHide(){
    dataCollection.setPageMapData('leave')
  },
  onUnload(){
    dataCollection.setPageMapData('leave')
  },
  onShow(){
    dataCollection.setPageMapData('enter','问题问题')
  },
})